<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\VipOrder;
use think\Db;
use think\Log;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 统一假的支付回调接口
     * @ApiSummary (统一假的支付回调接口)
     * @ApiMethod (POST)
     * @ApiParams (name="order_no", type="string", required=true, description="订单号")
     * @ApiParams (name="order_type", type="string", required=true, description="订单类型，可选值: vip, goods, travel, service")
     */
    public function fakePayNotify()
    {
        $orderNo = $this->request->post('order_no');
        $orderType = $this->request->post('order_type');

        if (empty($orderNo) || empty($orderType)) {
            $this->error('参数错误：订单号和订单类型不能为空');
        }

        Log::info("FakePayNotify: order_no=[".$orderNo."], order_type=[".$orderType."]");

        Db::startTrans();
        try {
            switch ($orderType) {
                case 'vip':
                    $order = VipOrder::getByOrderNo($orderNo);
                    if ($order && $order->status == VipOrder::STATUS_UNPAID) {
                        // 更新订单状态
                        $order->status = VipOrder::STATUS_PAID;
                        $order->pay_time = time();
                        $order->save();
                        
                        // 更新用户会员时间
                        $user = \app\common\model\User::get($order->user_id);
                        $user->vip_expire_time = $order->expire_time;
                        $user->save();

                        // 获取会员配置信息
                        $vipConfig = \app\common\model\VipConfig::get($order->vip_config_id);
                        if ($vipConfig && $vipConfig->voucher_times > 0) {
                            // 生成代金券记录
                            for ($i = 0; $i < $vipConfig->voucher_times; $i++) {
                                \app\common\model\UserVoucher::create([
                                    'user_id' => $order->user_id,
                                    'vip_order_id' => $order->id,
                                    'teacher_ids' => $vipConfig->teacher_ids,
                                    'status' => 0, // 0=未使用
                                    'expire_time' => $order->expire_time,
                                    'createtime' => time()
                                ]);
                            }
                        }
                        
                        // 创建系统消息
                        \app\common\model\SystemMessage::create([
                            'user_id' => $order->user_id,
                            'type' => 'vip',
                            'title' => '下单成功 (模拟支付)',
                            'content' => "感谢您的信任，您的会员已开通，会员到期时间为" . date('Y-m-d H:i:s', $order->expire_time),
                            'order_id' => $order->id,
                            'order_no' => $order->order_no
                        ]);
                        
                        // 记录用户消费记录
                        Db::name('user_consume_log')->insert([
                            'user_id' => $order->user_id,
                            'type' => 'vip',
                            'target_id' => $order->vip_config_id,
                            'target_title' => $vipConfig->title,
                            'amount' => -$order->amount,
                            'createtime' => time()
                        ]);
                        Log::info("FakePayNotify: VIP order [{$orderNo}] processed.");
                    } else {
                        $this->error('VIP订单不存在或已支付');
                    }
                    break;
                case 'goods':
                    $order = \app\common\model\Order::where([
                        'order_no' => $orderNo,
                        'status' => 0 // 待支付状态
                    ])->find();
                    if ($order) {
                        // 更新订单状态为已支付
                        $order->status = 1;
                        $order->pay_time = time();
                        // $order->pay_type = 'fake'; // 可以标记为假支付
                        // $order->transaction_id = 'FAKE_' . $orderNo;
                        $order->save();
                        
                        // 更新商品销量
                        foreach ($order->items as $item) {
                            \app\common\model\Goods::where('id', $item->goods_id)
                                ->setInc('sales', $item->quantity);
                        }
                        
                        // 创建系统消息
                        \app\common\model\SystemMessage::create([
                            'user_id' => $order->user_id,
                            'type' => 'goods',
                            'title' => '下单成功 (模拟支付)',
                            'content' => "感谢您的信任，您购买的【{$order->items[0]->goods->title}】已下单成功，订单将在48小时内发货，请及时关注物流变化",
                            'order_id' => $order->id,
                            'order_no' => $order->order_no
                        ]);
                        
                        // 记录用户消费记录
                        Db::name('user_consume_log')->insert([
                            'user_id' => $order->user_id,
                            'type' => 'goods',
                            'target_id' => $order->items[0]->goods_id,
                            'target_title' => $order->items[0]->goods->title,
                            'amount' => -$order->amount,
                            'createtime' => time()
                        ]);
                        Log::info("FakePayNotify: Goods order [{$orderNo}] processed.");
                    } else {
                        $this->error('商品订单不存在或已支付');
                    }
                    break;
                case 'travel':
                    $order = \app\common\model\TravelOrder::where([
                        'order_no' => $orderNo,
                        'status' => \app\common\model\TravelOrder::STATUS_UNPAID
                    ])->find();
                    if ($order) {
                        // 更新订单状态为已支付
                        $order->status = \app\common\model\TravelOrder::STATUS_PAID;
                        $order->pay_time = time();
                        // $order->pay_type = 'fake';
                        // $order->transaction_id = 'FAKE_' . $orderNo;
                        $order->save();
                        
                        // 更新文旅信息销量
                        \app\common\model\Travel::where('id', $order->travel_id)
                            ->setInc('sales', $order->num);
                        
                        // 创建系统消息
                        \app\common\model\SystemMessage::create([
                            'user_id' => $order->user_id,
                            'type' => 'travel',
                            'title' => '下单成功 (模拟支付)',
                            'content' => "感谢您的信任，您购买的【{$order->title}】已下单成功，订单将在48小时内发货，请及时关注物流变化",
                            'order_id' => $order->id,
                            'order_no' => $order->order_no
                        ]);
                        
                        // 记录用户消费记录
                        Db::name('user_consume_log')->insert([
                            'user_id' => $order->user_id,
                            'type' => 'travel',
                            'target_id' => $order->travel_id,
                            'target_title' => $order->title,
                            'amount' => -$order->amount,
                            'createtime' => time()
                        ]);
                        Log::info("FakePayNotify: Travel order [{$orderNo}] processed.");
                    } else {
                        $this->error('文旅订单不存在或已支付');
                    }
                    break;
                case 'service':
                    $order = \app\common\model\ServiceOrder::where([
                        'order_no' => $orderNo,
                        'status' => \app\common\model\ServiceOrder::STATUS_UNPAID
                    ])->find();
                    if ($order) {
                        // 更新订单状态为已支付
                        $order->status = \app\common\model\ServiceOrder::STATUS_PAID;
                        $order->pay_time = time();
                        // $order->pay_type = 'fake';
                        // $order->transaction_id = 'FAKE_' . $orderNo;
                        $order->save();

                        // 创建系统消息
                        \app\common\model\SystemMessage::create([
                            'user_id' => $order->user_id,
                            'type' => 'service',
                            'title' => '下单成功 (模拟支付)',
                            'content' => "感谢您的信任，您预约的【{$order->service_name}】已支付成功，请等待老师确认",
                            'order_id' => $order->id,
                            'order_no' => $order->order_no
                        ]);

                        // 记录用户消费记录
                        Db::name('user_consume_log')->insert([
                            'user_id' => $order->user_id,
                            'type' => 'service',
                            'target_id' => $order->service_id,
                            'target_title' => $order->service_name,
                            'amount' => -$order->amount,
                            'createtime' => time()
                        ]);
                        Log::info("FakePayNotify: Service order [{$orderNo}] processed.");
                    } else {
                        $this->error('服务订单不存在或已支付');
                    }
                    break;
                default:
                    Db::rollback();
                    $this->error('无效的订单类型');
                    return;
            }
            Db::commit();
            $this->success('模拟支付成功');
        } catch (\think\exception\PDOException $e) {
            Db::rollback();
            Log::error("FakePayNotify Error: " . $e->getMessage());
            $this->error('模拟支付失败：' . $e->getMessage());
        }
    }
}
